<template>
  <div class="roles">
    <!-- 路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加btn -->
    <el-button type="success" plain class="addBtn" @click="showAdd">添加角色</el-button>
    <!-- 角色列表 -->
    <el-table ref="rolesList" :data="rolesList" style="width: 100%">
      <!-- 展开行内容 -->
      <el-table-column type="expand">
        <template v-slot:default="{ row }">
          <p v-if="row.children.length === 0">暂无数据</p>
          <el-row class="r1" v-for="r1 in row.children" :key="r1.id">
            <el-col :span="4">
              <el-tag closable @close="delRights(row, r1.id)">{{ r1.authName }}</el-tag>
              <span class="el-icon-arrow-right"></span>
            </el-col>
            <el-col :span="20">
              <el-row class="r2" v-for="r2 in r1.children" :key="r2.id">
                <el-col :span="4">
                  <el-tag closable @close="delRights(row, r2.id )" type="success">{{ r2.authName }}</el-tag>
                  <span class="el-icon-arrow-right"></span>
                </el-col>
                <el-col :span="20">
                  <el-tag
                    closable
                    @close="delRights(row, r3.id )"
                    type="warning"
                    class="r3"
                    v-for="r3 in r2.children"
                    :key="r3.id"
                  >{{ r3.authName }}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 初始显示内容 -->
      <el-table-column type="index" width="50" label="#"></el-table-column>
      <el-table-column property="roleName" label="角色名称"></el-table-column>
      <el-table-column property="roleDesc" label="描述"></el-table-column>
      <el-table-column label="操作">
        <template v-slot:default="{ row }">
          <el-button @click="showEdit(row)" type="primary" size="small" plain icon="el-icon-edit"></el-button>
          <el-button
            @click="delRole(row.id)"
            type="danger"
            size="small"
            plain
            icon="el-icon-delete"
          ></el-button>
          <el-button
            @click="showAssign(row)"
            type="success"
            size="small"
            plain
            icon="el-icon-check"
          >分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限框 -->
    <el-dialog title="分配权限" :visible.sync="assignVisible" width="40%">
      <el-tree
        ref="tree"
        :data="data"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        node-key="id"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignVisible = false">取 消</el-button>
        <el-button @click="assignRights" type="primary">分 配</el-button>
      </span>
    </el-dialog>

    <!-- 添加用户框 -->
    <el-dialog title="添加角色" :visible.sync="addVisible" width="40%">
      <el-form :rules="rules" ref="addForm" :model="addForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户框 -->
    <el-dialog title="修改角色" :visible.sync="editVisible" width="40%">
      <el-form :rules="rules" ref="editForm" :model="editForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [{}],
      assignVisible: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      roleId: '',
      addVisible: false,
      editVisible: false,
      rules: {
        roleName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change']
          }
        ]
      },
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleName: '',
        roleDesc: '',
        id: ''
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 渲染数据
    async getRolesList () {
      const { meta, data } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.rolesList = data
        // console.log(this.rolesList)
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 删除权限
    async delRights (row, rightId) {
      const { meta, data } = await this.$axios.delete(
        `roles/${row.id}/rights/${rightId}`
      )
      console.log(data)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        row.children = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 显示分配权限
    async showAssign (row) {
      this.roleId = row.id
      this.assignVisible = true
      // 一展示分配对话框, 就应该发送 ajax 请求, 获取的是 全部的权限列表(tree)
      const { data, meta } = await this.$axios.get('rights/tree')
      if (meta.status === 200) {
        // 成功了, 将数据存起来
        this.data = data
        // console.log(data)
        const ids = []
        row.children.forEach(r1 => {
          r1.children.forEach(r2 => {
            r2.children.forEach(r3 => {
              ids.push(r3.id)
            })
          })
        })
        this.$refs.tree.setCheckedKeys(ids)
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 分配权限
    async assignRights () {
      const ids = this.$refs.tree.getCheckedKeys()
      const halfs = this.$refs.tree.getHalfCheckedKeys()
      const rids = [...ids, ...halfs].join(',')

      const { meta } = await this.$axios.post(`roles/${this.roleId}/rights`, {
        rids
      })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.assignVisible = false
        this.getRolesList()
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 展示添加角色框
    showAdd () {
      this.addVisible = true
    },
    // 添加角色
    async addRole () {
      await this.$refs.addForm.validate()
      const { meta } = await this.$axios.post('roles', this.addForm)
      if (meta.status === 201) {
        this.$message.success(meta.msg)
        this.$refs.addForm.resetFields()
        this.addVisible = false
        this.getRolesList()
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 删除角色框
    async delRole (id) {
      // console.log(id)
      try {
        await this.$confirm('你确定要删除吗', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`roles/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.getRolesList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch {
        this.$message.error('有内鬼,交易终止')
      }
    },
    // 显示编辑角色框
    showEdit (row) {
      this.editForm.id = row.id
      this.editForm.roleName = row.roleName
      this.editForm.roleDesc = row.roleDesc
      this.editVisible = true
    },
    // 编辑角色
    async editRole () {
      const { meta } = await this.$axios.put(`roles/${this.editForm.id}`, this.editForm)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.editVisible = false
        this.getRolesList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style lang="scss" scope>
.roles {
  .addBtn {
    margin-bottom: 10px;
  }
  .r1 {
    margin: 10px;
    padding: 10px;
    border-bottom: 1px dotted #ccc;
  }
  .r2 {
    margin-bottom: 10px;
  }
  .r3 {
    margin: 0 5px 5px 0;
  }
}
</style>
